<template>
  <div class="farmer-orders-page">
    <div class="orders-container">
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="6">
            <div class="stat-card">
              <div class="stat-icon pending">📋</div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.pendingCount }}</div>
                <div class="stat-label">待处理订单</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="12" :sm="6">
            <div class="stat-card">
              <div class="stat-icon preparing">🌱</div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.preparingCount }}</div>
                <div class="stat-label">备货中</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="12" :sm="6">
            <div class="stat-card">
              <div class="stat-icon shipped">🚚</div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.shippedCount }}</div>
                <div class="stat-label">已发货</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="12" :sm="6">
            <div class="stat-card">
              <div class="stat-icon completed">✅</div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.completedCount }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 订单筛选 -->
      <div class="orders-filter">
        <div class="filter-tabs">
          <div
            v-for="tab in statusTabs"
            :key="tab.status"
            :class="['filter-tab', { active: activeStatus === tab.status }]"
            @click="activeStatus = tab.status"
          >
            <span class="tab-name">{{ tab.name }}</span>
            <span v-if="tab.count > 0" class="tab-count">{{ tab.count }}</span>
          </div>
        </div>
        
        <div class="filter-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索订单号、商品名称..."
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="date-picker"
          />
          <el-select v-model="productFilter" placeholder="商品筛选" clearable>
            <el-option
              v-for="product in availableProducts"
              :key="product.id"
              :label="product.name"
              :value="product.id"
            />
          </el-select>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="orders-list">
        <div v-if="filteredOrders.length === 0" class="empty-orders">
          <div class="empty-icon">📦</div>
          <p class="empty-text">暂无订单</p>
        </div>

        <div v-else class="order-items">
          <div
            v-for="order in paginatedOrders"
            :key="order.id"
            class="order-card"
          >
            <!-- 订单头部信息 -->
            <div class="order-header">
              <div class="order-basic-info">
                <div class="order-number-time">
                  <span class="order-number">订单号：{{ order.orderNumber }}</span>
                  <span class="order-time">下单时间：{{ formatTime(order.createTime) }}</span>
                  <span v-if="order.urgent" class="urgent-tag">加急</span>
                </div>
                <div class="order-status-section">
                  <span :class="['status-badge', getStatusClass(order.status)]">
                    {{ getStatusText(order.status) }}
                  </span>
                </div>
              </div>
              
              <!-- 买家信息 -->
              <div class="buyer-info">
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">买家：</span>
                    <span class="value">{{ order.buyerName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">电话：</span>
                    <span class="value">{{ order.buyerPhone }}</span>
                  </div>
                </div>
                <div class="info-item full-width">
                  <span class="label">收货地址：</span>
                  <span class="value">{{ order.shippingAddress }}</span>
                </div>
              </div>
            </div>

            <!-- 订单商品列表 -->
            <div class="order-products">
              <div
                v-for="item in order.items"
                :key="item.id"
                class="product-item"
              >
                <div class="product-image">
                  <img :src="item.image" :alt="item.name" />
                </div>
                <div class="product-details">
                  <div class="product-main-info">
                    <h4 class="product-name">{{ item.name }}</h4>
                    <p class="product-category">{{ getCategoryName(item.category) }}</p>
                    <div class="product-specs">
                      <span class="spec">重量：{{ item.weight }}kg</span>
                      <span class="spec">单价：¥{{ item.unitPrice.toFixed(2) }}</span>
                    </div>
                  </div>
                  <div class="product-quantity-price">
                    <div class="quantity">×{{ item.quantity }}</div>
                    <div class="total-price">¥{{ (item.unitPrice * item.quantity).toFixed(2) }}</div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 订单统计 -->
            <div class="order-summary">
              <div class="summary-left">
                <div class="summary-item">
                  <span class="label">商品总数：</span>
                  <span class="value">{{ getTotalQuantity(order) }}件</span>
                </div>
                <div class="summary-item">
                  <span class="label">订单金额：</span>
                  <span class="value total-amount">¥{{ order.totalAmount.toFixed(2) }}</span>
                </div>
                <div v-if="order.buyerNote" class="buyer-note">
                  <span class="label">买家备注：</span>
                  <span class="value">{{ order.buyerNote }}</span>
                </div>
              </div>
            </div>

            <!-- 订单操作 -->
            <div class="order-actions">
              <template v-if="order.status === 'pending'">
                <el-button type="primary" @click="acceptOrder(order.id)">
                  <el-icon><Check /></el-icon>
                  接单
                </el-button>
                <el-button @click="rejectOrder(order.id)">拒绝接单</el-button>
                <el-button @click="contactBuyer(order)">联系买家</el-button>
              </template>

              <template v-else-if="order.status === 'accepted'">
                <el-button type="primary" @click="startPreparing(order.id)">
                  <el-icon><Box /></el-icon>
                  开始备货
                </el-button>
                <el-button @click="contactBuyer(order)">联系买家</el-button>
                <el-button @click="updateProgress(order)">更新进度</el-button>
              </template>

              <template v-else-if="order.status === 'preparing'">
                <div class="progress-section">
                  <div class="progress-info">
                    <span class="progress-label">备货进度：</span>
                    <el-progress 
                      :percentage="order.progress || 0" 
                      :show-text="false"
                      class="progress-bar"
                    />
                    <span class="progress-text">{{ order.progress || 0 }}%</span>
                  </div>
                  <el-button type="primary" @click="shipOrder(order)">
                    <el-icon><Van /></el-icon>
                    发货
                  </el-button>
                </div>
                <div class="action-buttons">
                  <el-button @click="updateProgress(order)">更新进度</el-button>
                  <el-button @click="contactBuyer(order)">联系买家</el-button>
                </div>
              </template>

              <template v-else-if="order.status === 'shipped'">
                <el-button @click="viewLogistics(order)">查看物流</el-button>
                <el-button @click="contactBuyer(order)">联系买家</el-button>
                <el-button @click="remindConfirm(order.id)">提醒确认收货</el-button>
              </template>

              <template v-else-if="order.status === 'completed'">
                <el-button @click="contactBuyer(order)">联系买家</el-button>

              </template>
            </div>

            <!-- 订单进度时间线 -->
            <div class="order-timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="(event, index) in order.timeline"
                  :key="index"
                  :timestamp="formatTime(event.time)"
                  :type="getTimelineType(event.type)"
                >
                  {{ event.description }}
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section" v-if="filteredOrders.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="filteredOrders.length"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="showShipDialog"
      title="订单发货"
      width="500px"
    >
      <div class="ship-dialog" v-if="currentOrder">
        <el-form :model="shipForm" label-width="80px">
          <el-form-item label="快递公司">
            <el-select v-model="shipForm.logisticsCompany" placeholder="选择快递公司">
              <el-option label="顺丰速运" value="顺丰速运" />
              <el-option label="圆通速递" value="圆通速递" />
              <el-option label="中通快递" value="中通快递" />
              <el-option label="韵达快递" value="韵达快递" />
              <el-option label="申通快递" value="申通快递" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="运单号码">
            <el-input v-model="shipForm.trackingNumber" placeholder="请输入运单号码" />
          </el-form-item>
          <el-form-item label="发货备注">
            <el-input
              v-model="shipForm.notes"
              type="textarea"
              :rows="3"
              placeholder="可填写发货备注信息"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showShipDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">确认发货</el-button>
      </template>
    </el-dialog>

    <!-- 更新进度对话框 -->
    <el-dialog
      v-model="showProgressDialog"
      title="更新备货进度"
      width="400px"
    >
      <div class="progress-dialog" v-if="currentOrder">
        <div class="progress-slider">
          <span class="progress-label">当前进度：{{ progressValue }}%</span>
          <el-slider v-model="progressValue" :show-tooltip="true" />
        </div>
        <el-input
          v-model="progressNotes"
          type="textarea"
          :rows="3"
          placeholder="可填写进度说明（选填）"
          class="progress-notes"
        />
      </div>
      <template #footer>
        <el-button @click="showProgressDialog = false">取消</el-button>
        <el-button type="primary" @click="updateOrderProgress">更新进度</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Check, Box, Van } from '@element-plus/icons-vue'

// 订单状态
const ORDER_STATUS = {
  PENDING: 'pending',      // 待处理
  ACCEPTED: 'accepted',    // 已接单
  PREPARING: 'preparing',  // 备货中
  SHIPPED: 'shipped',      // 已发货
  COMPLETED: 'completed'   // 已完成
}

// 响应式数据
const activeStatus = ref('all')
const searchKeyword = ref('')
const dateRange = ref([])
const productFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const showShipDialog = ref(false)
const showProgressDialog = ref(false)
const currentOrder = ref(null)
const progressValue = ref(0)
const progressNotes = ref('')

// 商品列表
const availableProducts = ref([
  { id: 1, name: '有机西红柿' },
  { id: 2, name: '新鲜黄瓜' },
  { id: 3, name: '特价土鸡蛋' },
  { id: 4, name: '有机胡萝卜' }
])

// 发货表单
const shipForm = ref({
  logisticsCompany: '',
  trackingNumber: '',
  notes: ''
})

// 订单数据
const orders = ref([
  {
    id: 1,
    orderNumber: 'NO202412010001',
    status: ORDER_STATUS.PENDING,
    createTime: '2024-12-01 10:30:00',
    totalAmount: 45.8,
    buyerName: '张三',
    buyerPhone: '13800138000',
    shippingAddress: '北京市朝阳区建国路88号SOHO现代城A座1001室',
    buyerNote: '希望尽快发货，周末要用',
    urgent: true,
    items: [
      {
        id: 1,
        name: '有机西红柿',
        category: 'vegetable',
        weight: 1.2,
        unitPrice: 8.5,
        quantity: 2,
        image: 'https://images.unsplash.com/photo-1546470427-e212d0d553c3?w=300&h=200&fit=crop'
      }
    ],
    timeline: [
      {
        time: '2024-12-01 10:30:00',
        type: 'created',
        description: '买家提交订单'
      }
    ]
  },
  {
    id: 2,
    orderNumber: 'NO202411300001',
    status: ORDER_STATUS.ACCEPTED,
    createTime: '2024-11-30 14:20:00',
    totalAmount: 68.5,
    buyerName: '李四',
    buyerPhone: '13900139000',
    shippingAddress: '上海市浦东新区陆家嘴环路1000号汇亚大厦',
    buyerNote: '',
    urgent: false,
    items: [
      {
        id: 2,
        name: '特价土鸡蛋',
        category: 'egg',
        weight: 0.5,
        unitPrice: 18.8,
        quantity: 2,
        image: 'https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?w=300&h=200&fit=crop'
      }
    ],
    timeline: [
      {
        time: '2024-11-30 14:20:00',
        type: 'created',
        description: '买家提交订单'
      },
      {
        time: '2024-11-30 15:30:00',
        type: 'accepted',
        description: '农户已接单'
      }
    ]
  },
  {
    id: 3,
    orderNumber: 'NO202411280001',
    status: ORDER_STATUS.PREPARING,
    createTime: '2024-11-28 09:15:00',
    totalAmount: 32.4,
    buyerName: '王五',
    buyerPhone: '13600136000',
    shippingAddress: '广州市天河区珠江新城华夏路10号',
    buyerNote: '需要新鲜采摘的',
    progress: 60,
    urgent: false,
    items: [
      {
        id: 3,
        name: '新鲜黄瓜',
        category: 'vegetable',
        weight: 0.8,
        unitPrice: 6.0,
        quantity: 3,
        image: 'https://images.unsplash.com/photo-1449300079327-02f967c1cdee?w=300&h=200&fit=crop'
      }
    ],
    timeline: [
      {
        time: '2024-11-28 09:15:00',
        type: 'created',
        description: '买家提交订单'
      },
      {
        time: '2024-11-28 10:00:00',
        type: 'accepted',
        description: '农户已接单'
      },
      {
        time: '2024-11-29 08:30:00',
        type: 'preparing',
        description: '开始备货，进度30%'
      },
      {
        time: '2024-11-30 14:20:00',
        type: 'preparing',
        description: '备货进度更新至60%'
      }
    ]
  },
  {
    id: 4,
    orderNumber: 'NO202411250001',
    status: ORDER_STATUS.SHIPPED,
    createTime: '2024-11-25 16:45:00',
    totalAmount: 56.2,
    buyerName: '赵六',
    buyerPhone: '13500135000',
    shippingAddress: '深圳市南山区科技园南区',
    buyerNote: '',
    urgent: false,
    items: [
      {
        id: 4,
        name: '有机胡萝卜',
        category: 'vegetable',
        weight: 1.0,
        unitPrice: 12.5,
        quantity: 1,
        image: 'https://images.unsplash.com/photo-1445282768818-728615cc910a?w=300&h=200&fit=crop'
      }
    ],
    logistics: {
      company: '顺丰速运',
      trackingNumber: 'SF1234567890',
      shipTime: '2024-11-27 09:15:00'
    },
    timeline: [
      {
        time: '2024-11-25 16:45:00',
        type: 'created',
        description: '买家提交订单'
      },
      {
        time: '2024-11-26 08:30:00',
        type: 'accepted',
        description: '农户已接单'
      },
      {
        time: '2024-11-26 14:00:00',
        type: 'preparing',
        description: '开始备货'
      },
      {
        time: '2024-11-27 09:15:00',
        type: 'shipped',
        description: '已发货 - 顺丰速运 SF1234567890'
      }
    ]
  },
  {
    id: 5,
    orderNumber: 'NO202411200001',
    status: ORDER_STATUS.COMPLETED,
    createTime: '2024-11-20 11:20:00',
    totalAmount: 42.3,
    buyerName: '钱七',
    buyerPhone: '13400134000',
    shippingAddress: '杭州市西湖区文三路',
    buyerNote: '',
    urgent: false,
    items: [
      {
        id: 5,
        name: '新鲜菠菜',
        category: 'vegetable',
        weight: 0.5,
        unitPrice: 7.8,
        quantity: 2,
        image: 'https://images.unsplash.com/photo-1576045057995-568f588f82fb?w=300&h=200&fit=crop'
      }
    ],
    timeline: [
      {
        time: '2024-11-20 11:20:00',
        type: 'created',
        description: '买家提交订单'
      },
      {
        time: '2024-11-20 14:30:00',
        type: 'accepted',
        description: '农户已接单'
      },
      {
        time: '2024-11-21 09:00:00',
        type: 'preparing',
        description: '开始备货'
      },
      {
        time: '2024-11-22 10:15:00',
        type: 'shipped',
        description: '已发货 - 圆通速递 YT9876543210'
      },
      {
        time: '2024-11-23 16:30:00',
        type: 'completed',
        description: '买家已确认收货'
      }
    ]
  }
])

// 计算属性
const stats = computed(() => {
  const pendingCount = orders.value.filter(o => o.status === ORDER_STATUS.PENDING).length
  const preparingCount = orders.value.filter(o => o.status === ORDER_STATUS.PREPARING).length
  const shippedCount = orders.value.filter(o => o.status === ORDER_STATUS.SHIPPED).length
  const completedCount = orders.value.filter(o => o.status === ORDER_STATUS.COMPLETED).length

  return {
    pendingCount,
    preparingCount,
    shippedCount,
    completedCount
  }
})

const statusTabs = computed(() => {
  const pendingCount = stats.value.pendingCount
  const acceptedCount = orders.value.filter(o => o.status === ORDER_STATUS.ACCEPTED).length
  const preparingCount = stats.value.preparingCount
  const shippedCount = stats.value.shippedCount

  return [
    { status: 'all', name: '全部订单' },
    { status: ORDER_STATUS.PENDING, name: '待处理', count: pendingCount },
    { status: ORDER_STATUS.ACCEPTED, name: '已接单', count: acceptedCount },
    { status: ORDER_STATUS.PREPARING, name: '备货中', count: preparingCount },
    { status: ORDER_STATUS.SHIPPED, name: '已发货', count: shippedCount },
    { status: ORDER_STATUS.COMPLETED, name: '已完成' }
  ]
})

const filteredOrders = computed(() => {
  let filtered = orders.value

  // 按状态筛选
  if (activeStatus.value !== 'all') {
    filtered = filtered.filter(order => order.status === activeStatus.value)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(order => 
      order.orderNumber.toLowerCase().includes(keyword) ||
      order.items.some(item => item.name.toLowerCase().includes(keyword)) ||
      order.buyerName.toLowerCase().includes(keyword)
    )
  }

  // 按商品筛选
  if (productFilter.value) {
    filtered = filtered.filter(order => 
      order.items.some(item => item.id.toString() === productFilter.value)
    )
  }

  // 按时间筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const [start, end] = dateRange.value
    filtered = filtered.filter(order => {
      const orderTime = new Date(order.createTime)
      return orderTime >= start && orderTime <= end
    })
  }

  return filtered
})

const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

// 方法
const getStatusText = (status) => {
  const statusMap = {
    [ORDER_STATUS.PENDING]: '待处理',
    [ORDER_STATUS.ACCEPTED]: '已接单',
    [ORDER_STATUS.PREPARING]: '备货中',
    [ORDER_STATUS.SHIPPED]: '已发货',
    [ORDER_STATUS.COMPLETED]: '已完成'
  }
  return statusMap[status] || '未知状态'
}

const getStatusClass = (status) => {
  const classMap = {
    [ORDER_STATUS.PENDING]: 'pending',
    [ORDER_STATUS.ACCEPTED]: 'accepted',
    [ORDER_STATUS.PREPARING]: 'preparing',
    [ORDER_STATUS.SHIPPED]: 'shipped',
    [ORDER_STATUS.COMPLETED]: 'completed'
  }
  return classMap[status] || 'unknown'
}

const getTimelineType = (type) => {
  const typeMap = {
    created: 'primary',
    accepted: 'success',
    preparing: 'warning',
    shipped: 'info',
    completed: 'success'
  }
  return typeMap[type] || 'primary'
}

const getCategoryName = (category) => {
  const categories = {
    vegetable: '蔬菜',
    fruit: '水果',
    egg: '禽蛋'
  }
  return categories[category] || category
}

const getTotalQuantity = (order) => {
  return order.items.reduce((sum, item) => sum + item.quantity, 0)
}

const formatTime = (timeString) => {
  return new Date(timeString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const goToDashboard = () => {
  console.log('跳转到工作台')
}

const goToProducts = () => {
  console.log('跳转到商品管理')
}

// 订单操作方法
const acceptOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要接单吗？', '确认接单', {
      confirmButtonText: '确认接单',
      cancelButtonText: '取消'
    })

    const orderIndex = orders.value.findIndex(o => o.id === orderId)
    if (orderIndex !== -1) {
      orders.value[orderIndex].status = ORDER_STATUS.ACCEPTED
      orders.value[orderIndex].timeline.push({
        time: new Date().toISOString(),
        type: 'accepted',
        description: '农户已接单'
      })
      ElMessage.success('接单成功！')
    }
  } catch (error) {
    // 用户点击了取消
  }
}

const rejectOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要拒绝这个订单吗？', '拒绝接单', {
      confirmButtonText: '确认拒绝',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const orderIndex = orders.value.findIndex(o => o.id === orderId)
    if (orderIndex !== -1) {
      orders.value.splice(orderIndex, 1)
      ElMessage.success('订单已拒绝')
    }
  } catch (error) {
    // 用户点击了取消
  }
}

const startPreparing = (orderId) => {
  const orderIndex = orders.value.findIndex(o => o.id === orderId)
  if (orderIndex !== -1) {
    orders.value[orderIndex].status = ORDER_STATUS.PREPARING
    orders.value[orderIndex].timeline.push({
      time: new Date().toISOString(),
      type: 'preparing',
      description: '开始备货'
    })
    ElMessage.success('已开始备货')
  }
}

const shipOrder = (order) => {
  currentOrder.value = order
  shipForm.value = {
    logisticsCompany: '',
    trackingNumber: '',
    notes: ''
  }
  showShipDialog.value = true
}

const confirmShip = () => {
  if (!shipForm.value.logisticsCompany || !shipForm.value.trackingNumber) {
    ElMessage.error('请填写完整的发货信息')
    return
  }

  const orderIndex = orders.value.findIndex(o => o.id === currentOrder.value.id)
  if (orderIndex !== -1) {
    orders.value[orderIndex].status = ORDER_STATUS.SHIPPED
    orders.value[orderIndex].logistics = {
      company: shipForm.value.logisticsCompany,
      trackingNumber: shipForm.value.trackingNumber,
      shipTime: new Date().toISOString()
    }
    orders.value[orderIndex].timeline.push({
      time: new Date().toISOString(),
      type: 'shipped',
      description: `已发货 - ${shipForm.value.logisticsCompany} ${shipForm.value.trackingNumber}`
    })
    
    showShipDialog.value = false
    ElMessage.success('发货成功！')
  }
}

const updateProgress = (order) => {
  currentOrder.value = order
  progressValue.value = order.progress || 0
  progressNotes.value = ''
  showProgressDialog.value = true
}

const updateOrderProgress = () => {
  const orderIndex = orders.value.findIndex(o => o.id === currentOrder.value.id)
  if (orderIndex !== -1) {
    orders.value[orderIndex].progress = progressValue.value
    
    let description = `备货进度更新至${progressValue.value}%`
    if (progressNotes.value) {
      description += ` - ${progressNotes.value}`
    }
    
    orders.value[orderIndex].timeline.push({
      time: new Date().toISOString(),
      type: 'preparing',
      description: description
    })
    
    showProgressDialog.value = false
    ElMessage.success('进度更新成功！')
  }
}

const contactBuyer = (order) => {
  ElMessage.info(`联系买家：${order.buyerName}，电话：${order.buyerPhone}`)
}

const viewLogistics = (order) => {
  ElMessage.info(`查看物流：${order.logistics.company} - ${order.logistics.trackingNumber}`)
}

const remindConfirm = (orderId) => {
  ElMessage.success('已发送确认收货提醒')
}

onMounted(() => {
  console.log('农户订单页面加载完成')
})
</script>

<style scoped>
.farmer-orders-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

/* 统计卡片 */
.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.pending {
  background: #fef3c7;
  color: #d97706;
}

.stat-icon.preparing {
  background: #d1fae5;
  color: #065f46;
}

.stat-icon.shipped {
  background: #dbeafe;
  color: #1d4ed8;
}

.stat-icon.completed {
  background: #dcfce7;
  color: #16a34a;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

/* 订单筛选 */
.orders-filter {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.filter-tabs {
  display: flex;
  gap: 0;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-tab {
  padding: 12px 24px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.filter-tab:hover {
  color: #10b981;
}

.filter-tab.active {
  color: #10b981;
  border-bottom-color: #10b981;
}

.tab-count {
  background: #ef4444;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
  min-width: 20px;
  text-align: center;
}

.filter-actions {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.date-picker {
  width: 240px;
}

/* 订单列表 */
.empty-orders {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 12px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.3;
}

.empty-text {
  color: #6b7280;
  font-size: 18px;
  margin-bottom: 20px;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 订单头部 */
.order-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.order-basic-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.order-number-time {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.order-number {
  font-weight: 600;
  color: #1f2937;
  font-size: 16px;
}

.order-time {
  color: #6b7280;
  font-size: 14px;
}

.urgent-tag {
  background: #fee2e2;
  color: #dc2626;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
}

.status-badge.pending {
  background: #fef3c7;
  color: #d97706;
}

.status-badge.accepted {
  background: #dbeafe;
  color: #1d4ed8;
}

.status-badge.preparing {
  background: #fef3c7;
  color: #d97706;
}

.status-badge.shipped {
  background: #d1fae5;
  color: #065f46;
}

.status-badge.completed {
  background: #f3f4f6;
  color: #6b7280;
}

.buyer-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.info-item.full-width {
  width: 100%;
}

.info-item .label {
  color: #6b7280;
  font-size: 14px;
}

.info-item .value {
  color: #1f2937;
  font-weight: 500;
}

/* 订单商品 */
.order-products {
  margin-bottom: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  margin-bottom: 12px;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-details {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.product-main-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.product-category {
  color: #6b7280;
  font-size: 14px;
  margin: 0 0 8px 0;
}

.product-specs {
  display: flex;
  gap: 16px;
}

.spec {
  color: #6b7280;
  font-size: 14px;
}

.product-quantity-price {
  text-align: right;
  min-width: 100px;
}

.quantity {
  color: #6b7280;
  margin-bottom: 8px;
}

.total-price {
  font-size: 16px;
  font-weight: 600;
  color: #ef4444;
}

/* 订单统计 */
.order-summary {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.summary-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.summary-item .label {
  color: #6b7280;
}

.summary-item .value {
  color: #1f2937;
  font-weight: 500;
}

.total-amount {
  color: #ef4444;
  font-size: 18px;
  font-weight: 600;
}

.buyer-note {
  background: #f0f9ff;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 3px solid #0ea5e9;
}

.buyer-note .label {
  color: #0c4a6e;
  font-weight: 500;
}

.buyer-note .value {
  color: #0369a1;
}

/* 订单操作 */
.order-actions {
  margin-bottom: 20px;
}

.progress-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
}

.progress-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.progress-label {
  color: #6b7280;
  font-size: 14px;
  min-width: 80px;
}

.progress-bar {
  flex: 1;
  max-width: 200px;
}

.progress-text {
  color: #1f2937;
  font-weight: 500;
  min-width: 40px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 订单时间线 */
.order-timeline {
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
}

/* 对话框样式 */
.ship-dialog,
.progress-dialog {
  padding: 20px 0;
}

.progress-slider {
  margin-bottom: 20px;
}

.progress-label {
  display: block;
  margin-bottom: 12px;
  color: #1f2937;
  font-weight: 500;
}

.progress-notes {
  margin-top: 16px;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .farmer-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .stats-cards .el-col {
    margin-bottom: 16px;
  }
  
  .filter-tabs {
    justify-content: center;
  }
  
  .filter-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .date-picker {
    width: 100%;
  }
  
  .order-basic-info {
    flex-direction: column;
    gap: 12px;
  }
  
  .order-number-time {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .info-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .product-details {
    flex-direction: column;
    gap: 12px;
  }
  
  .progress-section {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .progress-info {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .progress-bar {
    max-width: none;
  }
  
  .action-buttons {
    justify-content: center;
  }
}
</style>